import Vue from "vue";
import store from "../store";
// import { Button } from "element-ui";
Vue.directive("drag", {
  bind(el, binding) {
    console.log(binding);
    console.log(el);
    // 鼠标按下
    el.onmousedown = (e) => {
      let cyBtn = document.createElement("div"); //复制一份el主体
      let lefts = "";
      let mainList = {};
      console.log(cyBtn);
      cyBtn.setAttribute("id", "drag"); //给标签添加一个id
      cyBtn.style.position = "absolute"; //修改元素的熟悉感
      cyBtn.style.width = "168px";
      cyBtn.style.lineHeight = "28px";
      cyBtn.style.background = "#409EFF";
      cyBtn.style.textAlign = "center";
      cyBtn.innerHTML = JSON.parse(binding.value).name; //插入组件名
      let body = document.body; //获取body对象
      body.appendChild(cyBtn); //在body下面插入子节点的主题
      // 算出鼠标相对元素的位置
      let disX = e.clientX - el.offsetLeft; //x轴坐标
      let disY = e.clientY - el.offsetTop; //y轴坐标
      let top = "";
      document.onmousemove = (e) => {
        //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX; //  鼠标停留 计算出相对位置
        top = e.clientY - disY; //  鼠标停留 计算出相对位置
        document.querySelector("#drag").style.left = `${left}px`;
        document.querySelector("#drag").style.top = `${top}px`;
        lefts = left - document.querySelector("#center").offsetLeft;
      };
      // 鼠标松开
      document.onmouseup = () => {
        document.onmousemove = null; //清除移动事件
        document.onmouseup = null; //清除鼠标移开事件
        if (lefts > 0) {
          mainList = {
            id: `task_${parseInt(new Date().getTime() / 1000)}_${Math.ceil(
              Math.random() * 10
            )}`,
            x: lefts,
            y: top,
            ...JSON.parse(binding.value),
          };
          store.commit("mapListBtn", mainList); //存放带vuex中
        }
        document.getElementById("drag").remove(); //删除元素id
      };
    };
  },
});
